package com.example.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;

import java.util.concurrent.ThreadLocalRandom;

/**
 *  熔断降级示例
 *
 */
@Service
public class DegradeService {

    /**
     * 慢调用比例策略示例
     * 配置：最大RT=500ms，比例阈值=0.5，最小请求数=5，熔断时长=10s
     */
    @SentinelResource(
            value = "slowCallResource",
            blockHandler = "handleBlockException",
            fallback = "handleFallback"
    )
    public String slowCallMethod(String param) {
        // 模拟50%的请求响应时间超过500ms
        if (ThreadLocalRandom.current().nextBoolean()) {
            try {
                Thread.sleep(600); // 超过阈值
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        } else {
            try {
                Thread.sleep(200); // 正常响应
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        return "慢调用测试成功: " + param;
    }

    /**
     * 异常比例策略示例
     * 配置：比例阈值=0.3，最小请求数=5，熔断时长=5s
     */
    @SentinelResource(
            value = "errorRatioResource",
            blockHandler = "handleBlockException",
            fallback = "handleFallback"
    )
    public String errorRatioMethod(String param) {
        // 模拟30%的异常率
        if (ThreadLocalRandom.current().nextInt(100) < 30) {
            throw new RuntimeException("业务异常");
        }
        return "异常比例测试成功: " + param;
    }

    /**
     * 异常数策略示例
     * 配置：异常数=3，最小请求数=5，熔断时长=5s
     */
    @SentinelResource(
            value = "errorCountResource",
            blockHandler = "handleBlockException",
            fallback = "handleFallback"
    )
    public String errorCountMethod(String param) {
        // 模拟固定概率的异常
        if (ThreadLocalRandom.current().nextInt(10) < 2) {
            throw new RuntimeException("业务异常");
        }
        return "异常数测试成功: " + param;
    }

    /**
     * 统一的BlockException处理
     */
    public String handleBlockException(String param, BlockException ex) {
        return "【熔断保护】系统繁忙，请稍后重试 (参数: " + param + ")";
    }

    /**
     * 统一的业务异常处理
     */
    public String handleFallback(String param) {
        return "【服务降级】功能暂时不可用 (参数: " + param + ")";
    }
}
